<template>
  <div class="container">
    <a-auto-complete
      class="input"
      :options="opts"
      v-model:value="input"
      placeholder="dataframe.query 的内容"
      @search="onSearch"
      @select="onSelect"
      :autofocus="true"
    />

    <a-button type="primary" @click="onApply" :disabled="!applyBtnDisplay"
      >应用</a-button
    >
  </div>
</template>

<script lang='ts'>
import { computed, defineComponent, reactive, ref } from "vue";
import * as apps from "@/applications";
import DfStore from "@/store/DfStore";

export default defineComponent({
  name: "Query",

  setup() {
    let input = ref("");
    let applyBtnDisplay = computed(() => input.value.length > 0);

    const opts = ref([] as object);

    const colInfos = DfStore.getStateReadonly().columnInfo;

    const onSelect = (value: any, option: any) => {
      input.value = option.text;
    };

    const onSearch = (searchText: any) => {
      opts.value = searchText ? searchResult(searchText) : [];

      function searchResult(query: any) {
        const arr: string[] = query.split(/\s+/);
        const value = arr.slice(-1)[0];

        return colInfos
          .filter((v) => v.field.indexOf(value) >= 0)
          .map((v) => {
            const value =
              arr.slice(0, arr.length - 1).join(" ") + " " + v.field;

            return {
              text: value.trim(),
              value: `${v.field}(${v.type})`,
            };
          });
      }
    };

    let onApply = async () => {
      await apps.filterByPandasQeury(input.value);
    };

    return {
      input,
      onApply,
      applyBtnDisplay,
      opts,
      onSearch,
      onSelect,
    };
  },
});
</script>


<style lang="less" scoped>
div.container {
  text-align: center;
}

.input {
  width: 50vw;
}
</style>

